package application;

import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Rectangle;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;

public class ReceptionWindow extends JFrame {

	private static final long serialVersionUID = 1L;
	private JPanel jContentPane = null;
	private JLabel descriptionLabel = null;
	private int progress = 0;
	private int length;
	private long lastTimeIndex;
	private float speed = 0;
	private JLabel progressLabel = null;
	private JTextArea textPane = null;
	private JScrollPane jScrollPane = null;

	/**
	 * This is the default constructor
	 */
	public ReceptionWindow(String source, int length) {
		super();
		this.length = length;
		initialize(source, length);
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize(String source, int length) {
		this.setSize(516, 400);
		this.setContentPane(getJContentPane(source, length));
		this.setTitle(ApplicationLayer.myID + " - From: " + source);
	}

	/**
	 * This method initializes jContentPane
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJContentPane(String source, int length) {
		if (jContentPane == null) {
			progressLabel = new JLabel();
			progressLabel.setBounds(new Rectangle(14, 44, 479, 20));
			progressLabel.setText("Received " + progress + " / " + length
					+ " parts.");
			lastTimeIndex = System.currentTimeMillis();
			descriptionLabel = new JLabel();
			descriptionLabel.setBounds(new Rectangle(14, 14, 479, 19));
			descriptionLabel.setText("Message received from " + source);
			jContentPane = new JPanel();
			jContentPane.setLayout(null);
			jContentPane.add(descriptionLabel, null);
			jContentPane.add(progressLabel, null);
			jContentPane.add(getJScrollPane(), null);
		}
		return jContentPane;
	}

	public void addText(String text) {
		long newTimeIndex = System.currentTimeMillis();
		speed = (speed * progress + (float) text.length()
				/ (newTimeIndex - lastTimeIndex) * 1000)
				/ (progress + 1);
		progress++;
		progressLabel.setText("Received " + progress + " / " + length
				+ " parts at speed " + speed + " bytes per second.");
		textPane.setText(textPane.getText() + text);
		lastTimeIndex = newTimeIndex;
	}

	/**
	 * This method initializes textPane
	 * 
	 * @return javax.swing.JTextArea
	 */
	private JTextArea getTextPane() {
		if (textPane == null) {
			textPane = new JTextArea();
		}
		return textPane;
	}

	/**
	 * This method initializes jScrollPane
	 * 
	 * @return javax.swing.JScrollPane
	 */
	private JScrollPane getJScrollPane() {
		if (jScrollPane == null) {
			jScrollPane = new JScrollPane();
			jScrollPane.setBounds(new Rectangle(15, 75, 481, 271));
			jScrollPane.setViewportView(getTextPane());
		}
		return jScrollPane;
	}

} // @jve:decl-index=0:visual-constraint="9,-5"
